import json
import re

from django.contrib.auth import login
from django.http import JsonResponse
from django.shortcuts import render


from django.views import View
from django_redis import get_redis_connection

from apps.users.models import User

# # 判断手机号是否重复注册
# class MobileCount(View):
#     def post(self,request):
#         mobile = request.GET.get('mobile')
#         try:
#             count = User.objects.filter(mobile=mobile).count
#         except:
#             return JsonResponse({'errno':4001,'errmsg':'查询数据库错误'})
#
#         return JsonResponse({'errno':0,'errmsg':'OK','count':count})
# 用户注册
from iHome.settings.dev import logger


class RegisterView(View):
    def post(self,request):
        #1. 获取参数并进行参数校验
        # 2. 从redis中获取指定手机号对应的短信验证码的
        # 3. 校验验证码
        # 4. 初始化 user 模型，并设置数据并添加到数据库
        # 5. 保存当前用户的状态
        # 6. 返回注册的结果
        # :return:
        # 提取参数
        json_dict = json.loads(request.body)
        mobile = json_dict.get('mobile') # 获取手机号
        sms_code = json_dict.get('phonecode') # 短信验证码
        password = json_dict.get('password') # 获取密码
        password2 = json_dict.get('password2') # 获取二次密码

        # 校验参数
        if not all([mobile,sms_code,password,password2]):
            return JsonResponse({'errno':4002,'errmsg':'缺少必传参数'})
        if not re.match(r'^1[3-9]\d{9}$',mobile):
            return JsonResponse({'errno':4004,'errmsg':'手机号格式错误'})
        if password != password2:
            return JsonResponse({'errno':4106,'errmsg':'两次密码输入不一致'})

        # 对比短信验证码
        client = get_redis_connection('verify_code')
        redis_sms_code = client.get(f'sms_{mobile}')
        if not redis_sms_code:
            return JsonResponse({'errno':4002,'errmsg':'验证码已过期'})

        # 注意：redis数据库提取的数据是二进制格式
        if sms_code != redis_sms_code.decode():
            return JsonResponse({'errno':4004,'errmsg':'短信验证码错误'})

        # 保存到数据库
        try:
            user = User.objects.create_user(
                username=mobile,
                mobile=mobile,
                password=password
            )
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno':4002,'errmsg':'注册失败'})

        # 状态保持
        login(request,user)

        return JsonResponse({'errno':0,'errmsg':'OK'})
import logging

from django.contrib.auth import authenticate, login, logout
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View

from apps.users.models import User
from utils.views import LoginRequiredJSONMixin

logger = logging.getLogger('django')

# 登录逻辑
class LoginView(View):
    def post(self, request):
        json_dict = json.loads(request.body)
        mobile = json_dict.get('mobile')
        password = json_dict.get('password')
        # remembered = json_dict.get('remembered')
        # if re.match('^1[3-9]\d{9}$', username):
        #     User.USERNAME_FIELD = 'mobile'
        if not all([mobile, password]):
            return JsonResponse({'errno':4103, 'errmsg':'PARAMERR'})

        try:
            user = User.objects.get(mobile=mobile)
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno':4104, 'errmsg':'USERERR'})
        if not user.check_password(password):
            return JsonResponse({'errno':4106, 'errmsg':'PWDERR'})
        login(request, user)
        # if remembered:
        #     # 记住登录状态
        #     request.session.set_expiry(None)
        # else:
        #     # 不记住登录状态
        #     request.session.set_expiry(0)
        response = JsonResponse({'errno':0, 'errmsg':'OK'})
        response.set_cookie('username', user.username, max_age=24 * 3600 *  14)
        return response


# 用户状态查询逻辑
class SessionView(View):
    def get(self, request):
        user = request.user
        if user.is_authenticated:
            data = {'user_id':user.id, 'name':user.username}
            return JsonResponse({'errno':0, 'errmsg':'OK', 'data':data})
        else:
            return JsonResponse({'errno':4101, 'errmsg':'SESSIONERR'})


# 退出登录逻辑
class LogoutView(LoginRequiredJSONMixin, View):
    def delete(self,request):
        logout(request)
        return JsonResponse({'errno':0, 'errmsg':'OK'})

from django.http import JsonResponse
from django.views.generic import View
from django import http

from apps.house.models import House
from apps.users.models import User

from iHome.utils import constants

from iHome.utils.image_storage import storage
from iHome.utils.response_code import RET
import logging

from iHome.utils.views import LoginRequiredJSONMixin

logger = logging.getLogger('django')


class Hose_sourse_View(View):

    def post(self, request, house_id):
        print(house_id)
        # house_id = House.objects.get(id=2)

        # 1:提取参数
        image_file = request.FILES.get('index_image_url')
        # 2:校验参数
        if image_file is None:
            return JsonResponse({
                "errno": 400,
                "errmsg": "图片没有输入，不能上传"
            }, status=400)

        # 3:数据处理---读取数据(二进制)，上传到七牛云，将返回的地址，保存到数据库
        image_data = image_file.read()

        try:
            file_name = storage(image_data)

        except Exception as e:
            print(e)
            return JsonResponse({
                "code": 400,
                "errmsg": "图片上传失败"
            })
        url = constants.QINIU_DOMIN_PREFIX + file_name
        try:
            # house = HouseImage.objects.create(house=house_id, url=file_name)
            print(house_id)
            house = House.objects.get(pk=house_id)
            house.index_image_url = url
            house.save()

        except Exception as e:
            print(e)
            return JsonResponse({
                "code": 400,
                "errmsg": "图片保存失败"
            })

        # 4：构建响应
        return JsonResponse({
            "data": {
                "url": url
            },
            "errno": "0",
            "errmsg": "图片上传成功",
        })








# 上次用户头像
class UserAvatar(View):

    def post(self, request):

        user = request.user
        # user = User.objects.get(id=1)
        # 1:提取参数
        image_file = request.FILES.get('avatar')

        # 2:校验参数
        if image_file is None:
            return JsonResponse({
                "code": 400,
                "errmsg": "图片没有输入，不能上传"
            }, status=400)

        # 3:数据处理---读取数据(二进制)，上传到七牛云，将返回的地址，保存到数据库
        image_data = image_file.read()

        try:
            file_name = storage(image_data)

        except Exception as e:
            return JsonResponse({
                "code":400,
                "errmsg": "图片上传失败"
            })

        avatar_url = constants.QINIU_DOMIN_PREFIX + file_name

        try:
            User.objects.filter(pk=user.id).update(avatar_url=avatar_url)

        except Exception as e:
            print(e)
            return JsonResponse({
                "code": 400,
                "errmsg": "图片保存失败"
            })


        # 4:构建响应
        return JsonResponse({
            "errno": 0,
            "errmsg": "ok",
             "data": {"avatar_url": avatar_url},
        })

# 获取、修改用户信息
class UserProfile(LoginRequiredJSONMixin, View):
    '''用户信息获取修改'''

    def get(self, request):
        '''获取用户信息
        1.获取当前登录用户
        2.返回用户信息
        '''

        # 1.获取当前登录用户
        user = request.user
        # 2.返回用户信息
        data = {
            "name": user.username,
            "avatar_url": user.avatar_url,
            "mobile": user.username
        }
        return http.JsonResponse({'errno': RET.OK, 'errmsg': "OK", 'data': data})

    def post(self, request):
        """
        1. 获取到传入参数
        2. 将用户名信息更新到当前用户的模型中
        3. 返回结果
        """

        # 1. 获取到传入参数
        data_dict = json.loads(request.body.decode())
        name = data_dict.get("name")
        if name is None:
            return http.JsonResponse({'errno': RET.PARAMERR, 'errmsg': "参数不完整"})

        # 2. 获取当前登录用户/更新用户名
        user = request.user
        try:

            user.username = name
            user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'errno': RET.DBERR, 'errmsg': "保存数据失败"})

        return http.JsonResponse({'errno': RET.OK, 'errmsg': "OK"})

# 获取、修改用户实名信息
class AuthProfile(LoginRequiredJSONMixin, View):
    '''用户真实信息获取和设置'''

    def get(self, request):
        """
        1. 取到当前登录用户
        2. 获取当前用户的认证信息
        3. 返回信息
        """
        # 1. 取到当前登录用户
        user = request.user

        # 2. 获取当前用户的认证信息
        auth_dict = {
            "real_name": user.real_name,
            "id_card": user.id_card
        }
        # 3. 返回信息
        return http.JsonResponse({'errno': RET.OK, 'errmsg': "OK", 'data': auth_dict})

    def post(self, request):
        """
        1. 取到当前登录用户
        2. 取到传过来的认证的信息
        3. 更新用户的认证信息
        4. 返回结果
        """

        # 1. 取到当前登录用户
        user = request.user

        # 2. 取到传过来的认证的信息
        data_dict = json.loads(request.body.decode())
        real_name = data_dict.get("real_name")
        id_card = data_dict.get("id_card")

        # 3. 更新用户的认证信息
        user.real_name = real_name
        user.id_card = id_card
        try:
            user.save()
        except Exception as e:
            return http.JsonResponse({'errno': RET.DBERR, 'errmsg': "保存数据失败"})

        # 4. 返回结果
        return http.JsonResponse({'errno': RET.OK, 'errmsg': "OK"})
